<template>
  <div class="qr-code">
    <!-- 顶部标题 -->
    <div class="header-title">
      <h2>诺威新型建材有限公司</h2>
    </div>
    
    <!-- 二维码显示区域 -->
    <div class="qr-code-container">
      <div class="qr-code-wrapper">
        <div class="qr-code-display">
          <!-- 如果有真实二维码，显示图片；否则显示模拟图案 -->
          <img 
            v-if="qrCodeImage" 
            :src="qrCodeImage" 
            alt="二维码" 
            class="qr-code-img"
          />
          <div v-else class="qr-code-grid">
            <!-- 模拟二维码图案 -->
            <div class="qr-module" v-for="(row, rowIndex) in qrPattern" :key="rowIndex">
              <div 
                v-for="(cell, colIndex) in row" 
                :key="colIndex"
                :class="['qr-cell', { 'active': cell }]"
              ></div>
            </div>
          </div>
        </div>
        <div class="qr-code-info">
          <p class="company-name">诺威新型建材有限公司</p>
          <p class="scan-tip">请扫描二维码</p>
        </div>
      </div>
      
      <!-- 功能按钮 -->
      <div class="action-buttons">
        <div class="action-button generate" @click="handleGenerate">
          <van-icon name="refresh" size="20" />
          <span>重新获取</span>
        </div>
        <div class="action-button save" @click="handleSave">
          <van-icon name="down" size="20" />
          <span>保存图片</span>
        </div>
      </div>
    </div>

    <!-- 底部导航 -->
    <van-tabbar v-model="active" class="custom-tabbar" @change="onTabChange">
      <van-tabbar-item icon="home-o">
        <span>首页</span>
      </van-tabbar-item>
      <van-tabbar-item icon="qr">
        <span>二维码</span>
      </van-tabbar-item>
      <van-tabbar-item icon="user-o">
        <span>我的</span>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { useRouter } from 'vue-router'
import { getWechatOpenId } from '../store.js'
import api from '../api/index.js'

const active = ref(1) // 当前页面是二维码页面
const router = useRouter()
const qrCodeImage = ref('') // 存储二维码图片的 base64 数据
const loading = ref(false)

// 模拟二维码图案 (21x21的简化版本) - 作为默认占位图
const qrPattern = reactive([
  [1,1,1,1,1,1,1,0,1,0,0,1,0,1,1,1,1,1,1,1,1],
  [1,0,0,0,0,0,1,0,0,1,1,0,1,1,0,0,0,0,0,0,1],
  [1,0,1,1,1,0,1,0,1,0,1,1,0,1,0,1,1,1,0,0,1],
  [1,0,1,1,1,0,1,0,0,0,1,0,1,1,0,1,1,1,0,0,1],
  [1,0,1,1,1,0,1,0,1,1,0,1,0,1,0,1,1,1,0,0,1],
  [1,0,0,0,0,0,1,0,0,0,1,1,1,1,0,0,0,0,0,0,1],
  [1,1,1,1,1,1,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1],
  [0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0],
  [1,0,1,1,0,1,1,1,1,0,1,0,1,1,1,0,1,0,0,1,0],
  [0,1,0,0,1,0,0,0,0,1,0,1,0,0,0,1,0,1,1,0,1],
  [1,0,1,1,0,1,1,1,0,0,1,0,1,1,0,0,1,0,0,1,0],
  [0,1,0,0,1,0,0,0,1,1,0,1,0,0,1,1,0,1,1,0,1],
  [1,0,1,1,0,1,1,1,0,0,1,0,1,1,0,0,1,0,0,1,0],
  [0,0,0,0,0,0,0,0,1,1,0,1,0,0,1,1,0,1,1,0,1],
  [1,1,1,1,1,1,1,0,0,0,1,0,1,1,0,0,1,0,0,1,0],
  [1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,1,1,0,1],
  [1,0,1,1,1,0,1,0,0,0,1,0,1,1,0,0,1,0,0,1,0],
  [1,0,1,1,1,0,1,0,1,1,0,1,0,0,1,1,0,1,1,0,1],
  [1,0,1,1,1,0,1,0,0,0,1,0,1,1,0,0,1,0,0,1,0],
  [1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,1,1,0,1],
  [1,1,1,1,1,1,1,0,0,0,1,0,1,1,0,0,1,0,0,1,0]
])

// 获取二维码
const fetchQRCode = async () => {
  try {
    loading.value = true
    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    })
    
    // 从 localStorage 获取 openid
    const fwid = getWechatOpenId()
    
    console.log('获取到的 OpenID:', fwid)
    
    if (!fwid) {
      closeToast()
      showToast('未获取到微信ID，请先从首页授权')
      // 跳转到首页
      setTimeout(() => {
        router.push('/')
      }, 2000)
      return
    }
    
    // 调用后端接口获取二维码
    const response = await api.getWaybillQRCode(fwid)
    
    console.log('二维码接口返回:', response)
    
    if (response && response.code === 200 && response.data) {
      // 后端返回的是 base64 编码的图片数据
      qrCodeImage.value = 'data:image/png;base64,' + response.data
      closeToast()
      console.log('二维码获取成功')
    } else {
      closeToast()
      showToast(response?.msg || '获取二维码失败')
      console.error('二维码获取失败:', response)
    }
  } catch (error) {
    closeToast()
    console.error('获取二维码出错:', error)
    showToast('网络异常，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取二维码
onMounted(() => {
  fetchQRCode()
})

// 底部导航切换
const onTabChange = (index) => {
  switch (index) {
    case 0:
      router.push('/')
      break
    case 1:
      // 当前页面，不需要跳转
      break
    case 2:
      router.push('/profile')
      break
  }
}

// 重新获取二维码
const handleGenerate = () => {
  fetchQRCode()
}

// 保存二维码图片
const handleSave = () => {
  if (!qrCodeImage.value) {
    showToast('暂无二维码可保存')
    return
  }
  
  try {
    // 创建一个下载链接
    const link = document.createElement('a')
    link.href = qrCodeImage.value
    link.download = '诺威建材预约二维码.png'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    showToast('二维码已保存')
  } catch (error) {
    console.error('保存二维码失败:', error)
    showToast('保存失败，请长按图片保存')
  }
}
</script>

<style scoped>
/* 全局样式优化 - 禁止滚动，强制一页显示 */
.qr-code {
  background: linear-gradient(180deg, #f8faff 0%, #f0f4ff 100%);
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 顶部标题美化 - 精简尺寸 */
.header-title {
  text-align: center;
  padding: 20px 0 16px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  flex-shrink: 0;
}

.header-title::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: shimmer 3s ease-in-out infinite;
}

@keyframes shimmer {
  0%, 100% { transform: translate(-50%, -50%) rotate(0deg); }
  50% { transform: translate(-50%, -50%) rotate(180deg); }
}

.header-title h2 {
  font-size: 20px;
  font-weight: 600;
  color: white;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
  letter-spacing: 1px;
  position: relative;
  z-index: 1;
}

/* 二维码容器 */
.qr-code-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  gap: 24px;
}

.qr-code-wrapper {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  position: relative;
  overflow: hidden;
}

.qr-code-wrapper::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.02), rgba(118, 75, 162, 0.02));
  pointer-events: none;
}

.qr-code-display {
  position: relative;
  z-index: 1;
}

/* 真实二维码图片样式 */
.qr-code-img {
  width: 240px;
  height: 240px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  background: white;
  padding: 8px;
  object-fit: contain;
}

.qr-code-grid {
  display: grid;
  grid-template-columns: repeat(21, 1fr);
  grid-template-rows: repeat(21, 1fr);
  gap: 1px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.qr-module {
  display: contents;
}

.qr-cell {
  width: 8px;
  height: 8px;
  background: #f5f5f5;
  border-radius: 1px;
  transition: all 0.3s ease;
}

.qr-cell.active {
  background: #2c3e50;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.qr-code-info {
  text-align: center;
  position: relative;
  z-index: 1;
}

.company-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
  letter-spacing: 0.5px;
}

.scan-tip {
  font-size: 14px;
  color: #8f9bb3;
  margin: 0;
}

/* 功能按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
  width: 100%;
  max-width: 300px;
}

.action-button {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 16px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(102, 126, 234, 0.1);
  position: relative;
  overflow: hidden;
}

.action-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
  transition: left 0.5s;
}

.action-button:hover::before {
  left: 100%;
}

.action-button:active {
  transform: translateY(2px) scale(0.98);
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}

.action-button.generate {
  color: #667eea;
}

.action-button.save {
  color: #26C6DA;
}

.action-button span {
  font-size: 14px;
  font-weight: 500;
  position: relative;
  z-index: 1;
}

/* 底部导航美化 */
.custom-tabbar {
  background: white;
  border-top: 1px solid rgba(102, 126, 234, 0.1);
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
  backdrop-filter: blur(10px);
  padding: 2px 0;
  min-height: 48px;
  flex-shrink: 0;
}

.custom-tabbar .van-tabbar-item {
  color: #8f9bb3;
  transition: all 0.3s ease;
}

.custom-tabbar .van-tabbar-item--active {
  color: #667eea;
  font-weight: 600;
}

.custom-tabbar .van-tabbar-item--active .van-icon {
  transform: scale(1.1);
}

/* 响应式优化 */
@media screen and (max-width: 375px) {
  .header-title h2 {
    font-size: 18px;
  }
  
  .qr-code-container {
    padding: 16px;
    gap: 20px;
  }
  
  .qr-code-wrapper {
    padding: 20px;
  }
  
  .qr-cell {
    width: 7px;
    height: 7px;
  }
  
  .action-button {
    padding: 14px 16px;
  }
}

@media screen and (max-height: 667px) {
  .qr-code-container {
    gap: 16px;
  }
  
  .qr-code-wrapper {
    padding: 20px;
  }
  
  .qr-cell {
    width: 6px;
    height: 6px;
  }
}

/* 加载动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes qrCodeScan {
  0% {
    transform: scale(0.95);
    opacity: 0.8;
  }
  50% {
    transform: scale(1.02);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.qr-code-wrapper {
  animation: fadeInUp 0.6s ease forwards, qrCodeScan 2s ease 0.6s;
}

.action-button:nth-child(1) {
  animation: fadeInUp 0.6s ease 0.8s forwards;
}

.action-button:nth-child(2) {
  animation: fadeInUp 0.6s ease 0.9s forwards;
}
</style>